package com.platform.system.logic;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.platform.common.constant.Constants;
import com.platform.common.utils.bean.BeanUtils;
import com.platform.system.domain.dto.AiRequestDto;
import com.platform.system.domain.dto.device.*;
import com.platform.system.domain.entity.device.HumanModelManager;
import com.platform.system.domain.vo.AiContentVo;
import com.platform.system.domain.vo.AiuiBodyVo;
import com.platform.system.domain.vo.device.WebUserInfoVo;
import com.platform.system.enums.ModelTypeEnum;
import com.platform.system.enums.TopicEnums;
import com.platform.system.model.BaseModelHandle;
import com.platform.system.mqtt.utils.MqttService;
import com.platform.system.service.ISysAiUiConfigService;
import com.platform.system.service.ISysHumanModelManagerService;
import com.platform.system.service.ISysModelAppInfoService;
import com.platform.system.service.ISysWebUserInfoService;
import com.tencentcloudapi.tiems.v20190416.models.ModelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.*;

/**
 * @author Huangkai
 */
@Slf4j
@Component
public class DeviceInfoLogic {

    @Resource
    ISysWebUserInfoService sysWebUserInfoService;

    @Resource
    ISysModelAppInfoService sysModelAppInfoService;

    @Resource
    ISysHumanModelManagerService sysHumanModelManagerService;

    @Resource
    ISysAiUiConfigService sysAiUiConfigService;

    @Resource
    HumanModelManagerLogic humanModelManagerLogic;

    @Resource
    AiLogic aiLogic;

    @Resource
    MqttService mqttService;

    public void publishDeviceInfo(DeviceInfoDto deviceInfoDto){
        buildDeviceInfoDetail(deviceInfoDto);
        HumanModelManagerDto humanModelManagerDto = deviceInfoDto.getHumanModelManagerDto();
        if(humanModelManagerDto != null){
            HumanModelManager humanModelManager = new HumanModelManager();
            BeanUtils.copyProperties(humanModelManagerDto, humanModelManager);
            List<HumanModelManagerDto> humanModelManagerDtoList = new ArrayList<>();
            humanModelManagerLogic.selectSpeakerInfoListDetail(Lists.newArrayList(humanModelManager), humanModelManagerDtoList);
            deviceInfoDto.setHumanModelManagerDto(humanModelManagerDtoList.get(0));

            ModelAppInfoDto modelAppInfoDto = deviceInfoDto.getModelAppInfoDto();
            if(modelAppInfoDto != null && !StringUtils.isEmpty(modelAppInfoDto.getModelParam())){
                modelAppInfoDto.setModelParamJson(JSONObject.parseObject(modelAppInfoDto.getModelParam()));
            }
        }

        //发送mqtt
        List<String> clientIdList = Lists.newArrayList(deviceInfoDto.getAuthKey());
        String deviceInfoDtoJson = JSONObject.toJSONString(deviceInfoDto);
        log.info("设备信息{}", deviceInfoDtoJson);
        mqttService.publishToClient(clientIdList, TopicEnums.DEVICE_INFO.topic, deviceInfoDtoJson);

    }

    public void buildDeviceInfoDetail(DeviceInfoDto deviceInfoDto){
        //查询模型信息
        if(StringUtils.isNotEmpty(deviceInfoDto.getModelAppUid())){
            ModelAppInfoDto modelAppInfoDto = sysModelAppInfoService.selectModelAppInfo(deviceInfoDto.getModelAppUid());
            if(modelAppInfoDto != null){
                deviceInfoDto.setModelAppInfoDto(modelAppInfoDto);
            }
        }
        //查询人设
        if(StringUtils.isNotEmpty(deviceInfoDto.getHumanCharacterUid())){
            HumanModelManagerDto humanModelManagerDto = sysHumanModelManagerService.selectHumanModelManager(deviceInfoDto.getHumanCharacterUid());
            if(humanModelManagerDto != null){
                deviceInfoDto.setHumanModelManagerDto(humanModelManagerDto);
            }
        }

        //aiui
        if(StringUtils.isNotEmpty(deviceInfoDto.getAiuiUid())){
            AiUiConfigDto aiUiConfigDto = sysAiUiConfigService.selectAiUiConfig(deviceInfoDto.getAiuiUid());
            if(aiUiConfigDto != null){
                deviceInfoDto.setAiUiConfigDto(aiUiConfigDto);
            }
        }
    }

    public void buildDeviceInfo(DeviceInfoDto deviceInfoDto){
        //查询用户
        if(StringUtils.isNotEmpty(deviceInfoDto.getWebUserUid())){
            log.info("设备用户信息{}", deviceInfoDto.getWebUserUid());
            WebUserInfoVo webUserInfoVo = new WebUserInfoVo();
            webUserInfoVo.setUid(deviceInfoDto.getWebUserUid());
            WebUserInfoDto webUserInfoDto = sysWebUserInfoService.selectWebUser(webUserInfoVo);
            deviceInfoDto.setUserName(webUserInfoDto.getPhone());
        }
        //查询模型信息
        if(StringUtils.isNotEmpty(deviceInfoDto.getModelAppUid())){
            ModelAppInfoDto modelAppInfoDto = sysModelAppInfoService.selectModelAppInfo(deviceInfoDto.getModelAppUid());
            if(modelAppInfoDto != null){
                deviceInfoDto.setAiModelName(modelAppInfoDto.getName());
            }
        }
        //查询人设
        if(StringUtils.isNotEmpty(deviceInfoDto.getHumanCharacterUid())){
            HumanModelManagerDto humanModelManagerDto = sysHumanModelManagerService.selectHumanModelManager(deviceInfoDto.getHumanCharacterUid());
            if(humanModelManagerDto != null){
                deviceInfoDto.setHumanName(humanModelManagerDto.getName());
            }
        }
    }

    public String authAiui(HttpServletRequest request, String token){
        Map<String, String[]> parameterMap = request.getParameterMap();
        ArrayList<String> signList = new ArrayList<>();
        signList.add(token);
        signList.add(parameterMap.get("rand")[0]);
        signList.add(parameterMap.get("timestamp")[0]);
        Collections.sort(signList);
        StringBuffer stringBuffer = new StringBuffer();
        for (String str : signList) {
            stringBuffer.append(str);
        }
        String shaEncode = DigestUtils.sha1Hex(stringBuffer.toString());
        log.info("加密的数据{}", shaEncode);
        return DigestUtils.sha1Hex(token);
    }

    public String aiuiDataOperation(HttpServletRequest request){
        log.info("aiui开始调用=================================================");
        StringBuilder builder = new StringBuilder();
        try{
            BufferedReader reader = request.getReader();
            String line = reader.readLine();
            while (line != null) {
                builder.append(line);
                line = reader.readLine();
            }
            reader.close();
            String reqBody = builder.toString();
            log.info("aiui传过来的信息{}", reqBody);
            AiuiBodyVo aiuiBodyVo = JSONObject.parseObject(reqBody, AiuiBodyVo.class);
            //获取body实体内容
            String contentBase64 = aiuiBodyVo.getMsg().getContent();
            byte[] base64decodedBytes = Base64.getDecoder().decode(contentBase64);
            String result = new String(base64decodedBytes, "utf-8");
            AiContentVo aiContentVo = JSONObject.parseObject(result, AiContentVo.class);
            //传古来的内容
            String text = aiContentVo.getIntent().getText();
            if(aiContentVo.getIntent().getRc() != null) {
                //如果等于4，则走大模型
                if (aiContentVo.getIntent().getRc() == Constants.NUM_FOUR) {
                    String userParams = aiuiBodyVo.getUserParams();
                    //获取设备信息
                    byte[] otherParamsByte = Base64.getDecoder().decode(userParams);
                    //获取deviceId
                    String otherParamsJson = new String(otherParamsByte, "utf-8");
                    //获取额外的参数
                    DeviceInfoDto deviceInfoDto = JSONObject.parseObject(otherParamsJson).toJavaObject(DeviceInfoDto.class);
                    if(!StringUtils.isEmpty(deviceInfoDto.getModelAppUid())){
                        ModelAppInfoDto modelAppInfoDto = sysModelAppInfoService.selectModelAppInfo(deviceInfoDto.getModelAppUid());
                        if(modelAppInfoDto == null ){
                            ModelTypeEnum modelTypeEnum = ModelTypeEnum.findEnumByCode(modelAppInfoDto.getModelType());
                            BaseModelHandle baseModelHandle = aiLogic.getMap().get(modelTypeEnum.getCode());
                            log.info("是否为空{}", baseModelHandle);
                            JSONObject jsonObject = JSONObject.from(modelAppInfoDto);
                            AiRequestDto aiRequestDto = baseModelHandle.requestAi(jsonObject);
                            log.info("aiui查询结果{}", aiRequestDto);
                        }
                    }
                }
            }
            JSONObject customData = new JSONObject();
            customData.put("key", "custom");
            customData.put("content", text);
            return customData.toJSONString();
        }catch (Exception exception){
            exception.printStackTrace();
            return null;
        }

    }
}
